#!/bin/awk -f
## assuming first layer is fixed, and ignoring everything but the second layer
BEGIN{
#  sel=ARGV[1]; ARGV[1]="-"; ARGC=2;
  show2d=0;
}
FNR==1{
  nn=$1; mu=$2; nt=$3;
#  nt=10;
#  print nn,mu,nt;
}
FNR>1&&FNR<4{ba=ba$0"\n"} #basis
FNR==3{
#  print nn,mu;
  nnl=nn/mu;
  for(i=1;i<=nt;i++){ # tilings
#    print "tiling "i > "/dev/stderr";    
    for(k=1;k<=mu;k++){ # layers
#      print "layer "k;
      ss[k]=""; st[k]="";
      for(j=1;j<=nnl;j++){ # nodes
	getline;
	nu=nuoffs($0);
	for(l=1;l<=5;l++){
	  ss[k]=ss[k]""$l;
	  if(l<5){
	    ss[k]=ss[k]" ";
	  }else{
	    ss[k]=ss[k]"   "nu"\n";
	  }
	}
	if(nu==2){
	  for(l=1;l<=5;l++){
	    st[k]=st[k]""$l;
	    if(l<5){
	      st[k]=st[k]" ";
	    }else{
	      st[k]=st[k]"\n";
	    }
	  }
	}
      }
    }
    s=""; t="";
    if(st[1]!=st[2]){
      for(k=1;k<=2;k++){ # again layers
	s=s""ss[k];
	t=t""st[k];
      }
      n[t]++; 
      if(n[t]==1){
	mt++;
	double[mt]=s;
	second[mt]=ss[2];
	ti[mt]=t;
#	ti[t]=s;
#	l1[mt]=st[1];
#	l2[mt]=st[2];
      }
    }
  }
}
END{
  split(FILENAME,a,".");
  rep=a[1]".tsta";
  out=a[1]".two";
  out2=a[1]".2nd";
  for(i=1;i<=mt;i++){
  }
  i=0; for(x in n){i++};
  print mt" tilings -> "out;
  print mt" tilings -> "out > rep;
  for(i=1;i<=mt;i++){
    print i,n[ti[i]]>>rep;
  };
  nna=nn/mu;
  print nna*2,"2",mt" # tilestat2: out of "nt>out;
  printf ba>>out;
  for(i=1;i<=mt;i++){
    printf double[i]>>out;
  };
  print nna,"1",mt" # sort+stat: out of "nt>out2;
  printf ba>>out2;
  for(i=1;i<=mt;i++){
    printf second[i]>>out2;
  };
}
function nuoffs(x, a,i,mn){
  split(x,a); mn=2;
  for(i=1;i<=5;i++){
    mn+=a[i];
  }
  if(mn<0){mn=-mn};
  while(mn>2){
    mn-=5;
  }
  if(mn<0){mn=-mn}
  return mn;
}
